"""
AI测试助手 - FastAPI后端主应用
"""

import os
import logging
import asyncio
from fastapi import FastAPI, HTTPException, Depends, status, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from starlette.middleware.base import BaseHTTPMiddleware

from app.core.config import settings
from app.core.database import engine, Base
from app.api.v1 import auth, analysis, requirements, test_cases, prompts, api_automation, ui_automation, dashboard, menu
from app.core.security import get_current_user

# 设置Hugging Face镜像站点
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),  # 输出到控制台
    ]
)

# 设置特定库的日志级别，减少噪音
# SQLAlchemy相关日志
logging.getLogger('sqlalchemy').setLevel(logging.ERROR)           # 完全关闭SQLAlchemy日志
logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)    # 关闭SQL语句日志
logging.getLogger('sqlalchemy.pool').setLevel(logging.ERROR)      # 关闭连接池日志
logging.getLogger('sqlalchemy.dialects').setLevel(logging.ERROR)  # 关闭方言日志
logging.getLogger('sqlalchemy.orm').setLevel(logging.ERROR)       # 关闭ORM日志
logging.getLogger('sqlalchemy.engine.Engine').setLevel(logging.ERROR)  # 关闭引擎日志

# HTTP相关日志
logging.getLogger('urllib3').setLevel(logging.WARNING)            # 关闭HTTP请求日志
logging.getLogger('httpx').setLevel(logging.WARNING)              # 关闭HTTPX日志
logging.getLogger('httpcore').setLevel(logging.WARNING)           # 关闭HTTP核心日志
logging.getLogger('multipart').setLevel(logging.WARNING)          # 关闭文件上传日志
logging.getLogger('watchfiles').setLevel(logging.WARNING)         # 关闭文件监控日志

logger = logging.getLogger(__name__)


class TimeoutMiddleware(BaseHTTPMiddleware):
    """请求超时中间件"""
    
    def __init__(self, app, timeout: float = 300.0):
        super().__init__(app)
        self.timeout = timeout
    
    async def dispatch(self, request: Request, call_next):
        try:
            # 设置请求超时
            return await asyncio.wait_for(call_next(request), timeout=self.timeout)
        except asyncio.TimeoutError:
            logger.error(f"请求超时: {request.url}")
            return JSONResponse(
                status_code=504,
                content={"detail": f"请求超时，处理时间超过 {self.timeout} 秒"}
            )


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    logger.info("🚀 AI测试助手服务启动中...")
    logger.info(f"🌐 HF镜像: {os.environ.get('HF_ENDPOINT', 'default')}")
    # 启动时创建数据库表
    Base.metadata.create_all(bind=engine)
    logger.info("✅ 数据库初始化完成")
    logger.info("🎉 服务启动成功！监听端口: 8000")
    yield
    # 关闭时的清理操作
    logger.info("👋 服务正在关闭...")


# 创建FastAPI应用
app = FastAPI(
    title="AI测试助手",
    description="基于AI的需求分析和测试用例生成系统",
    version="2.0.0",
    lifespan=lifespan
)

# 添加超时中间件
app.add_middleware(TimeoutMiddleware, timeout=300.0)  # 5分钟超时

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router, prefix="/api/v1/auth", tags=["认证"])
app.include_router(analysis.router, prefix="/api/v1/analysis", tags=["AI分析"])
app.include_router(requirements.router, prefix="/api/v1/requirements", tags=["需求管理"])
app.include_router(test_cases.router, prefix="/api/v1/test-cases", tags=["测试用例"])
app.include_router(prompts.router, prefix="/api/v1/prompts", tags=["提示词管理"])
app.include_router(api_automation.router, prefix="/api/v1/api-automation", tags=["接口自动化"])
app.include_router(ui_automation.router, prefix="/api/v1/ui-automation", tags=["UI自动化"])
app.include_router(dashboard.router, prefix="/api/v1/dashboard", tags=["仪表盘"])
app.include_router(menu.router, prefix="/api/v1/menu", tags=["菜单权限"])


@app.get("/")
async def root():
    """根路径"""
    return {"message": "AI测试助手 FastAPI 后端", "version": "2.0.0"}


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "AI测试助手"}


if __name__ == "__main__":
    import uvicorn
    # 配置uvicorn日志
    log_config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            },
            "access": {
                "format": "%(asctime)s - %(levelname)s - %(client_addr)s - %(request_line)s - %(status_code)s",
            },
        },
        "handlers": {
            "default": {
                "formatter": "default",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
            },
            "access": {
                "formatter": "access",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
            },
        },
        "loggers": {
            "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
            "uvicorn.error": {"level": "INFO"},
            "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
        },
    }
    
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_config=log_config,
        timeout_keep_alive=300,  # 保持连接超时时间设置为5分钟
        timeout_graceful_shutdown=30,  # 优雅关闭超时时间
        limit_concurrency=1000,  # 并发连接数限制
        limit_max_requests=10000,  # 最大请求数限制
        server_header=False,
        date_header=False
    ) 